import * as path from 'path';
import * as edge from 'electron-edge-js';
import * as os from 'os';


let fsPath;
let filePath;

export class WinUSB {
    private libm;
    private onOpenHandle: number;
    private winDriver_FindUSBPrinter;
    private winDriver_Print2USB;
    private winDriver_Open;
    // private winDriver_Check;

    get isWin7() {
        if (os.platform() == 'win32' && os.release().indexOf('10.0.') == -1) {
            return true;
        }
        return false;
    }
    constructor(private pid: any, private vid: any) {
        if (!filePath) {
            filePath = path.resolve('./resources/dll/USBPrinterSdk.dll');
        }

        if (!this.isWin7) {
            //如果不是win7 系统
            filePath = path.resolve('./resources/dll/win11/USBPrinterSdk.dll');
        }

        this.winDriver_FindUSBPrinter = edge.func({
            assemblyFile: filePath,
            typeName: 'USBPrinterSdk.USBPrinter',
            methodName: 'FindUSBPrinter'
        });
        this.winDriver_Print2USB = edge.func({
            assemblyFile: filePath,
            typeName: 'USBPrinterSdk.USBPrinter',
            methodName: 'Print2USB'
        });
        this.winDriver_Open = edge.func({
            assemblyFile: filePath,
            typeName: 'USBPrinterSdk.USBPrinter',
            methodName: 'Open'
        });
    }

    open(callback) {
        this.winDriver_Open({ vid: this.vid, pid: this.pid }, (error, result) => {
            console.log('USB', result, this.vid, this.pid);
            this.onOpenHandle = 1;
            callback && callback(null, this);
        });

        return this;
    }

    write(data: Buffer, callback) {
        let params = {
            printData: data,
            pid: this.pid,
            vid: this.vid,
            openHandle: this.onOpenHandle
        };

        this.winDriver_Print2USB(params, (error, result) => {
            console.log('winDriver_Print2USB', result);
            if (error) {
                console.error(error);
                callback && callback({
                    message: error.message || '打印错误！'
                })
            } else {
                if (result && result.length && (result[0] == 30)) {
                    error = {
                        message: '打印错误！'
                    };
                }
                callback && callback(error, result);
            }
        });
    }

    close(callback) {
        callback && callback(null, this);
        return this;
    }

    async findPrinter() {
        return new Promise((resolve, reject) => {
            this.winDriver_FindUSBPrinter('javascript', (err, result) => {
                if (err) {
                    reject(err);
                }
                else {
                    resolve(result);
                }
            });
        });
    }

}